package com.baiyu.common.utils.http;


import com.baiyu.common.utils.LogUtils;
import com.baiyu.common.utils.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.*;


/**
 * @author spingcin@hotmail.com
 * @version V1.0
 * @description HttpClient 工具类
 * @data 2021-2-4
 */
public class HttpClient4 {

    /**
     * @return String
     * @author spingcin@hotmail.com
     * @description 向指定 URL 发送 POST 请求
     */
    public static String doPost(String url, Map<String, Object> params) {
        CloseableHttpClient client = null;
        CloseableHttpResponse response = null;
        String result = "";

        // 创建httpClient实例
        client = HttpClients.createDefault();
        // 创建httpPost远程连接实例
        HttpPost post = new HttpPost(url);
        // 配置请求参数实例
        RequestConfig config = RequestConfig.custom().setConnectTimeout(35000)
                // 设置连接主机服务超时时间
                .setConnectionRequestTimeout(35000)
                // 设置连接请求超时时间
                .setSocketTimeout(60000)
                // 设置读取数据连接超时时间
                .build();
        // 为httpPost实例设置配置
        post.setConfig(config);
        // 设置请求头
        post.addHeader("Content-Type", "application/x-www-form-urlencoded");
        // 封装post请求参数
        if (null != params && params.size() > 0) {
            List<NameValuePair> nvps = new ArrayList<NameValuePair>();
            // 通过map集成entrySet方法获取entity
            Set<Map.Entry<String, Object>> entrySet = params.entrySet();
            // 循环遍历，获取迭代器
            Iterator<Map.Entry<String, Object>> iterator = entrySet.iterator();
            while (iterator.hasNext()) {
                Map.Entry<String, Object> mapEntry = iterator.next();
                Object o = mapEntry.getValue();
                String value = StringUtils.isNull(o) ? "" : String.valueOf(o);
                nvps.add(new BasicNameValuePair(mapEntry.getKey(), value));
            }

            // 为httpPost设置封装好的请求参数
            try {
                post.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8"));
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }

        try {
            // httpClient对象执行post请求,并返回响应参数对象
            response = client.execute(post);
            // 从响应对象中获取响应内容
            HttpEntity entity = response.getEntity();
            result = EntityUtils.toString(entity);
        } catch (Exception e) {
            LogUtils.logError("发送 Http Post 请求异常", e);
        } finally {
            // 关闭资源
            if (null != response) {
                try {
                    response.close();
                } catch (IOException e) {
                    LogUtils.logError("关闭 Http 响应异常", e);
                }
            }
            if (null != client) {
                try {
                    client.close();
                } catch (IOException e) {
                    LogUtils.logError("关闭 Http 异常", e);
                }
            }
        }
        return result;
    }

    /**
     * @return String
     * @author spingcin@hotmail.com
     * @description 向指定 URL 发送 GET 请求
     */
    public static String doGet(String url) {
        CloseableHttpClient client = null;
        CloseableHttpResponse response = null;
        String result = "";
        try {
            // 通过默认配置创建一个httpClient实例
            client = HttpClients.createDefault();
            // 创建httpGet远程连接实例
            HttpGet get = new HttpGet(url);
            // 设置配置请求参数
            RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(35000)
                    // 连接主机服务超时时间
                    .setConnectionRequestTimeout(35000)
                    // 请求超时时间
                    .setSocketTimeout(60000)
                    // 数据读取超时时间
                    .build();
            // 为httpGet实例设置配置
            get.setConfig(requestConfig);
            // 执行get请求得到返回对象
            response = client.execute(get);
            // 通过返回对象获取返回数据
            HttpEntity entity = response.getEntity();
            // 通过EntityUtils中的toString方法将结果转换为字符串
            result = EntityUtils.toString(entity);
        } catch (Exception e) {
            LogUtils.logError("发送 Http Get 请求异常", e);
        } finally {
            // 关闭资源
            if (null != response) {
                try {
                    response.close();
                } catch (IOException e) {
                    LogUtils.logError("关闭 Http 响应异常", e);
                }
            }
            if (null != client) {
                try {
                    client.close();
                } catch (IOException e) {
                    LogUtils.logError("关闭 Http 异常", e);
                }
            }
        }
        return result;
    }
}